﻿/*----------------------------------------------------------------
//  <copyright file="UserNickNameValidator.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2023-07-05 12:04</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.Identity
{
    #region "用户昵称验证器"
    /// <summary>
    /// 用户昵称验证器
    /// </summary>
    public class UserNickNameValidator<TUser, TUserKey> : IUserValidator<TUser>
        where TUser : UserBase<TUserKey>
        where TUserKey : struct, IEquatable<TUserKey>
    {
        #region "方法"
        #region "验证用户昵称合法性"
        /// <summary>
        /// 验证用户昵称合法性
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public virtual Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user)
        {
            IdentityResult result = IdentityResult.Success;
            TUser existUser = manager.Users.FirstOrDefault(m => m.NickName == user.NickName);
            if (existUser != null
                && (Equals(user.Id, default(TUserKey)) /*新注册用户，ID为默认值*/
                || !Equals(user.Id, existUser.Id)/*已存在用户不是要编辑的用户*/))
            {
                result = new IdentityResult().Failed(I18N.T("用户 {0} 已存在", user.NickName));
            }
            return Task.FromResult(result);
        }
        #endregion

        #endregion

    }
    #endregion

}
